// Copyright 2006 PR1ME. All Rights Reserved.

import java.util.BitSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class Centroid {

  public Centroid(int dimensions) {
    this.sums = new int[dimensions];
    this.total = 0;
  }

  public void add(BitSet bitSet) {
    for (int i = bitSet.nextSetBit(0); i >= 0; i = bitSet.nextSetBit(i + 1)) {
      ++sums[i];
    }
    ++total;
  }

  public String computeDescriptor(String[] wordList, int[] wordFrequency) {
    Set set = new TreeSet();
    for (int i = 0; i < sums.length; ++i) {
      if (sums[i] > 0) {
        set.add(new Rank(sums[i], wordFrequency[i], wordList[i]));
      }
    }
    String result = null;
    Iterator it = set.iterator();
    for (int i = 0; i < 3; ++i) {
      if (it.hasNext()) {
        Rank next = (Rank) it.next();
        if (i == 0) {
          result = next.getWord();
        } else {
          result += ", " + next.getWord();
        }
      }
    }
    return result;
  }

  public double distance(BitSet bitSet) {
    double d = 0;
    for (int i = 0; i < sums.length; ++i) {
      // compute this dimension's distance to center
      int s = sums[i];
      int t = total;
      if (bitSet.get(i)) {
        double dist = (t - s) / (double)t;
        d += dist;
      } else {
        double dist = s / (double)t;
        d += dist * dist;
      }
    }
    return d;
  }

  private int[] sums;
  private int total;
}
